package cn.itsource.template;

import cn.hutool.http.HttpUtil;
import cn.itsource.config.WechatConfig;
import cn.itsource.dto.AccessTokenResult;
import cn.itsource.dto.OpenIdResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 创建template工具类
 */
@Slf4j
public class WechatTemplate {
    private WechatConfig wechatConfig;

    public WechatTemplate() {
    }

    /**
     * 参数从自动配置类传过来的：WechatLoginAutoConfiguration
     * 参数就是以下：
     * private String appid;  wx78731d9d10bf4f99
     * private String secret; 98465a777f2d9982b3bbbce9400e3c33
     * private static String wechatUrl
      */


    public WechatTemplate(WechatConfig wechatConfig) {
        this.wechatConfig = wechatConfig;
    }
    //获取openid
    public String getOpenId(String code){
        //
        String url = String.format(WechatConfig.WECHAT_URL, wechatConfig.getAppid(), wechatConfig.getSecret(),code);
        // 糊涂工具包的请求
        String s = HttpUtil.get(url); //拿到的的值就含有openid，
        OpenIdResult openIdResult = JSON.parseObject(s, OpenIdResult.class); //转为json数据，在返回
//        System.err.println(openIdResult.getOpenid());
        return openIdResult.getOpenid();
    }

    //获取手机号的token
    public String getAccessToken(){
        String accessTokenUrl = String.format(WechatConfig.ACCESS_TOKEN_URL, wechatConfig.getAppid(), wechatConfig.getSecret());
        String s = HttpUtil.get(accessTokenUrl);
        AccessTokenResult accessTokenResult = JSONObject.parseObject(s, AccessTokenResult.class);
        return accessTokenResult.getAccess_token();
    }

    // 获取手机号
    public String getPhoneNumber(String accessToken,String code){
        String phoneUrl = String.format(WechatConfig.PHONE_NUMBER_URL, accessToken);
        HashMap<String, Object> body = new HashMap<>();
        body.put("code",code);
        String post = HttpUtil.post(phoneUrl,body);
        JSONObject jsonObject = JSON.parseObject(post);
        JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
        return phoneInfo.get("phoneNumber").toString();
    }

}
